﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using UnityEngine;

using System.Windows.Forms;
using Color = System.Drawing.Color;
using Graphics = System.Drawing.Graphics;
using Screen = System.Windows.Forms.Screen;

public partial class CutterForm : Form
{
        public Image shotImage;
        public CutterForm()
        {
            this.SuspendLayout();
            // 
            // Cutter
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "Cutter";
            this.Text = "Cutter";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.Load += new System.EventHandler(this.Cutter_Load);
            this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Cutter_MouseClick);
            this.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.Cutter_MouseDoubleClick);
            this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Cutter_MouseDown);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Cutter_MouseMove);
            this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Cutter_MouseUp);
            this.ResumeLayout(false);
        }
        #region 定义程序变量
        // 定义变量

        // 用来记录鼠标按下的坐标，用来确定绘图起点
        private Point DownPoint;

        // 用来表示是否截图完成
        private bool CatchFinished = false;

        // 用来表示截图开始
        private bool CatchStart = false;

        // 用来保存原始图像
        private Bitmap originBmp;

        // 用来保存截图的矩形
        private Rectangle CatchRectangle;
        #endregion


        /// <summary>
        /// 窗体初始化操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cutter_Load(object sender, EventArgs e)
        {
            // 设置控件样式为双缓冲，这样可以有效减少图片闪烁的问题
            // 第二个参数为true表示把第一个参数指定的样式应用于控件；false 表示不应用。
            // '|'表示位逻辑或运算
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
            this.UpdateStyles();
            // 改变鼠标样式
            this.Cursor = Cursors.Cross;
            // 保存全屏图片
            originBmp = new Bitmap(this.BackgroundImage);
        }
        /// <summary>
        /// 右键点击退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cutter_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Cutter_MouseDoubleClick(sender, e); // 双击事件监听不到，暂时用右键事件
                // this.DialogResult = DialogResult.OK;
                // this.Close();
            }
        }
        /// <summary>
        /// 左键按下开始截屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cutter_MouseDown(object sender, MouseEventArgs e)
        {
            // 鼠标左键按下是开始画图，也就是截图
            if (e.Button == MouseButtons.Left)
            {
                // 如果捕捉没有开始
                if (!CatchStart)
                {
                    CatchStart = true;
                    // 保存此时鼠标按下坐标
                    DownPoint = new Point(e.X, e.Y);
                }
            }
        }
        /// <summary>
        /// 左键双击保存到剪贴板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cutter_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // if (e.Button == MouseButtons.Left && CatchFinished) 
            if (CatchFinished)
            {
                // 新建一个与矩形一样大小的空白图片
                Bitmap CatchedBmp = new Bitmap(CatchRectangle.Width, CatchRectangle.Height);

                Graphics g = Graphics.FromImage(CatchedBmp);

                // 把originBmp中指定部分按照指定大小画到空白图片上
                // CatchRectangle指定originBmp中指定部分
                // 第二个参数指定绘制到空白图片的位置和大小
                // 画完后CatchedBmp不再是空白图片了，而是具有与截取的图片一样的内容
                g.DrawImage(originBmp, new Rectangle(0, 0, CatchRectangle.Width, CatchRectangle.Height), CatchRectangle, GraphicsUnit.Pixel);

                // 将图片保存到剪切板中
                Clipboard.SetImage(CatchedBmp);
                
                Cutter.ShotImage = CatchedBmp;
                
                g.Dispose();
                CatchFinished = false;
                this.BackgroundImage = originBmp;
                // CatchedBmp.Dispose();
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
        /// <summary>
        /// 鼠标移动事件处理程序，即用户改变截图大小的处理
        ///  这个方法是截图功能的核心方法，也就是绘制截图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cutter_MouseMove(object sender, MouseEventArgs e)
        {
            // 确保截图开始
            if (CatchStart)
            {
                // 新建一个图片对象，让它与屏幕图片相同
                Bitmap copyBmp = (Bitmap)originBmp.Clone();

                // 获取鼠标按下的坐标
                Point newPoint = new Point(DownPoint.X, DownPoint.Y);

                // 新建画板和画笔
                Graphics g = Graphics.FromImage(copyBmp);
                Pen p = new Pen(Color.Red, 1);

                // 获取矩形的长宽
                int width = Math.Abs(e.X - DownPoint.X);
                int height = Math.Abs(e.Y - DownPoint.Y);
                if (e.X < DownPoint.X)
                {
                    newPoint.X = e.X;
                }
                if (e.Y < DownPoint.Y)
                {
                    newPoint.Y = e.Y;
                }

                CatchRectangle = new Rectangle(newPoint, new Size(width, height));

                // 将矩形画在画板上
                g.DrawRectangle(p, CatchRectangle);

                // 释放目前的画板
                g.Dispose();
                p.Dispose();
                // 从当前窗体创建新的画板
                Graphics g1 = this.CreateGraphics();

                // 将刚才所画的图片画到截图窗体上
                // 为什么不直接在当前窗体画图呢？
                // 如果自己解决将矩形画在窗体上，会造成图片抖动并且有无数个矩形
                // 这样实现也属于二次缓冲技术
                g1.DrawImage(copyBmp, new Point(0, 0));
                g1.Dispose();
                // 释放拷贝图片，防止内存被大量消耗
                copyBmp.Dispose();
            }
        }
        /// <summary>
        /// 左键弹起结束截屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cutter_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 如果截图已经开始，鼠标左键弹起设置截图完成
                if (CatchStart)
                {
                    CatchStart = false;
                    CatchFinished = true;
                }
            }
        }
    }

public class Cutter
{
    public static void StartShot(Action<Texture> callBack)
    {
        // 新建一个和屏幕大小相同的图片
        Bitmap CatchBmp = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height);
        // 创建一个画板，让我们可以在画板上画图
        // 这个画板也就是和屏幕大小一样大的图片
        // 我们可以通过Graphics这个类在这个空白图片上画图
        Graphics g = Graphics.FromImage(CatchBmp);
        // 把屏幕图片拷贝到我们创建的空白图片 CatchBmp中
        g.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height));

        // 创建截图窗体
        Form cutterForm = new CutterForm();
        // 指示窗体的背景图片为屏幕图片
        cutterForm.BackgroundImage = CatchBmp;
        // 显示窗体
        //cutter.Show();
        // 如果Cutter窗体结束，则从剪切板获得截取的图片，并显示在聊天窗体的发送框中
        if (cutterForm.ShowDialog() == DialogResult.OK)
        {
            // return;
            // 清楚剪贴板的图片
            // Clipboard.Clear();
            if (Cutter.ShotImage != null)
            {
                callBack(Cutter.GetTextureByBitmap(Cutter.ShotImage));
            }
        }
    }
    
    private static Texture2D GetTextureByBitmap(System.Drawing.Bitmap bmp)
    {
        Texture2D t = new Texture2D(1,1);
        MemoryStream ms = new MemoryStream();
        bmp.Save(ms,bmp.RawFormat);
        t.LoadImage(ms.ToArray());
        return t;
    }
    
    public static System.Drawing.Bitmap ShotImage { get; set; }
}
